/**
*  \file    sadd.h
*
*  \brief   this module contains functions to add two values without overflow.
*           in case of an overflow, the data type limit will be returned.
*
*  \author  Francesco D'Aprea <francesco.daprea@linde-mh.de>
*           Yingqin Wu <yingqin.wu@linde-china.com>
*
*/

#ifndef SADD_H_INCLUDED
#define SADD_H_INCLUDED

/*================================================[ public includes  ]================================================*/
#include "../cfg/prj.h"

/*================================================[ public defines   ]================================================*/

#define SATURATED_ADD(T_VAL) \
   if ( val < (T_VAL)( T_VAL##_MAX - off ) ) \
   { \
      return (T_VAL)(val + off); \
   } \
   else \
   { \
      return T_VAL##_MAX; \
   }

/* saturated add */
STATIC_INLINE U8  saturated_add_U8( U8 val, U8 off )
{
   SATURATED_ADD( U8 )
}

STATIC_INLINE U16 saturated_add_U16( U16 val, U16 off )
{
   SATURATED_ADD( U16 )
}

STATIC_INLINE U32 saturated_add_U32( U32 val, U32 off )
{
   SATURATED_ADD( U32 )
}


#ifdef U64_MIN /* only if U64 is available */
/**
*  Saturated addition U64
*
*  The function sadd_u64 addition the passed value as long as this does not overflow,
*  and returns it. If it is overflow U64_MAX will be return.
*
*   \param val  Value to be added.
*   \param off  Value to Add
*
*   \return The sum or U64_MAX .
*/
STATIC_INLINE U64 saturated_add_U64( U64 val, U64 off )
{
   SATURATED_ADD( U64 )
}
#endif

STATIC_INLINE S8  saturated_add_S8( S8 val, U8 off )
{
   SATURATED_ADD( S8 )
}

STATIC_INLINE S16 saturated_add_S16( S16 val, U16 off )
{
   SATURATED_ADD( S16 )
}

STATIC_INLINE S32 saturated_add_S32( S32 val, U32 off )
{
   SATURATED_ADD( S32 )
}

/*================================================[ public datatypes ]================================================*/

/*================================================[ public variables ]================================================*/

/*================================================[ public functions ]================================================*/


/*====================================================================================================================*/

#endif

/***********************************************************************************************************************
*                             Copyright 2010 Linde Material Handling. All rights reserved.                             *
***********************************************************************************************************************/
